import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";

import { SetofkeyService } from "../../../../service/setofkey.service";
import { Setofkey } from "../../../../entity/setofkey.model";
import { Command } from "../../../../shared/toolbar.service";
import { BladeData } from "../../../../shared/blade/blade-data";
import { Blade } from "../../../../shared/blade/blade.model";
import { DicValueListComponent } from "../dic-value-list/dic-value-list.component";

import { Subject } from "rxjs/Subject";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/of';

@Component({
    selector: 'app-dic-key-edit',
    templateUrl: './dic-key-edit.component.html',
    styleUrls: ['./dic-key-edit.component.css'],
})
export class DicKeyEditComponent extends BladeContainerBase<Setofkey>{
    constructor(
        private fb: FormBuilder,
        private setofkeyService: SetofkeyService) {
        super(fb);
    }
    ngOnInit(): void {
        //编辑时注册按钮和按钮命令    
        if (!this.isNew) {
            this.commands = [
                new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
                new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
                new Command("show", "键值列表", "fa fa-edit", "setofvalue:read", (blade) => this.exeShow(blade), (blade) => this.canShow(blade))
            ]
        }
        else {
            this.currentEntity = new Setofkey(0, "", "");
        }
        super.ngOnInit();
    }
    /**
    * 初始化数据
    * 
    * 
    * @memberof BladeContainerBase
    */
    initData(): any | Observable<any> | Promise<any> {
        this.formPatchValue(this.currentEntity);
    }

    exeSaveChange(blade: any): void {
        this.saveChange();
    }
    canSaveChange(blade: any): boolean {
        return this.hasChange() && !this.hasError();
    }
    exeReset(blade: any): void {
        return this.formGroup.reset(this.currentEntity);
    }
    canReset(blade: any): boolean {
        return this.hasChange();
    }
    exeShow(blade: any): void {
        if (this.bladeService.findBlade("dicValueList") == undefined) {
            let data: BladeData = new BladeData();
            data.id = "dicValueList";
            data.title = this.currentEntity.keyCode + "值列表";
            data.subtitle = this.currentEntity.keyDesc;
            data.isClosingDisabled = false;
            let dicValueListBlade = this.bladeService.createBlade(DicValueListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(dicValueListBlade, this.currentBlade);
        }
    }
    canShow(blade: any): boolean {
        return true;
    }
    /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
    createForm() {
        this.formGroup = this.fromBuider.group({
            "keyCode": [{ value: this.currentEntity.keyCode, disabled: !this.isNew }, [
                Validators.required,
                Validators.pattern("^[A-Za-z0-9]+$"),
                Validators.maxLength(100),
            ], (control: FormControl): any => this.keyCodeAsnyValidator(control)],
            "keyDesc": [this.currentEntity.keyDesc, [
                Validators.maxLength(100)
            ]],
        });
    }
    /**
    * 设置表单错误对象
    * 
    * 
    * @memberof BladeContainerBase
    */
    setFormError(): void {
        this.formErrors = {
            'keyCode': '',
            'keyDesc': ''
        };
    }
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            'keyCode': {
                'required': '键名称不能为空。',
                'maxlength': '键名称不能多于100个字符长度。',
                'pattern': '键名称必须由字母和数字组成。',
                'exist': '键名称已存在',
            },
            'keyDesc': {
                'maxlength': '键描述不能多于100个字符长度。',
            }
        };
    }
    /**
     * 异步校验keyCode是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof DicKeyEditComponent
     */
    keyCodeAsnyValidator(control: FormControl): any {
        if (this.isNew) {     
            return this.setofkeyService.hasSetofkeyByKeyCode(control.value, this.currentEntity.keyId)
                .map(res => res ? { exist: true } : null);
        }
        return Observable.of(null);
    }
    /**
     * 创建一个数据字典键
     * 
     * 
     * @memberof DicKeyEditComponent
     */
    onCreate() {
        this.create();
    }
    create(): Promise<boolean> {
        if (!this.hasError()) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value as Setofkey;
            this.currentEntity.keyCode = formValue.keyCode;
            this.currentEntity.keyDesc = formValue.keyDesc;
            return this.setofkeyService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
    saveChange(): Promise<boolean> {
        if (this.canSaveChange(this.currentBlade)) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value as Setofkey;
            this.currentEntity.keyCode = formValue.keyCode;
            this.currentEntity.keyDesc = formValue.keyDesc;
            return this.setofkeyService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);

        }
    }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/dic/dic-key-edit/dic-key-edit.component.ts